package trabalho3.model;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import model.org.jtrace.Hit;
import model.org.jtrace.Jay;
import model.org.jtrace.Material;
import model.org.jtrace.NotHit;
import model.org.jtrace.geometry.GeometricObject;
import model.org.jtrace.geometry.Triangle;
import action.org.jtrace.io.PlyReader;

public class MeshSphere extends GeometricObject {
	private BoundingBox box;
	private List<Triangle> triangles;
	
	
	public MeshSphere(Material material, boolean ativarBoundingBox) throws IOException {
		super(material);
		
		InputStream is = new FileInputStream(new File("ply/sphere.ply"));		
		PlyReader ply = new PlyReader(); 
		triangles = ply.read(is, material);
		
		if (ativarBoundingBox) {
			box = new BoundingBox(ply.getMinPoint(), ply.getMaxPoint());
		}
	}

	@Override
	public Hit hit(Jay jay) {
		//TODO implementar o metodo hit com base no bounding box
		double tMin = Double.MAX_VALUE;
        GeometricObject hitObject = null;
        Hit hitMin = new Hit();
        Hit triangleHit;
        Hit faceHit;
		for (Triangle face : box.getBoundingFaces()) {
			faceHit = face.hit(jay);
			
			if (faceHit.isHit()) {
				for (Triangle triangle : triangles) {
					triangleHit = triangle.hit(jay);
					
					if (triangleHit.isHit() && triangleHit.getT() < tMin) {
		                tMin = triangleHit.getT();
		                hitObject = triangle;
		                hitMin = triangleHit;
		            }
				}
				
				break;
			}
		}
		
		if (hitObject != null) {
			hitMin.setObject(hitObject);
	        return hitMin;
		} else {
			return new NotHit();
		}
	}
	
	public BoundingBox getBox() {
		return box;
	}
	
	public List<Triangle> getTriangles() {
		return triangles;
	}

}
